import Axios from 'axios'
import Cookies from 'js-cookie'
import { ElMessageBox, ElMessage } from 'element-plus'

// console.log(import.meta.env.VITE_API_DOMAIN)

const service = Axios.create({
  baseURL: import.meta.env.VITE_API_DOMAIN as string,
  timeout: 5000
})

service.interceptors.request.use(config => {
  const token = Cookies.get('token')
  if (token) {
    config.headers!['X-Requested-With'] = 'XMLHttpRequest'
    config.headers!['Authorization'] = token
  }
  return config
}, error => {
  console.log('request: ', error)
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  if (response.headers.authorization) {
    Cookies.set('token', response.headers.authorization)
  }
  const res = response.data
  if (response.data.hasOwnProperty("code")) {
    if (res.code !== 200) {
      ElMessage({
        message: res.msg || res.message || res.status || 'Error',
        type: 'error'
      })

      if (res.code === 401) {
        ElMessageBox.confirm('您已注销，您可以取消停留在此页面, 或重新登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Cookies.remove('token')
          location.reload()
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  }else{
    return res
  }
  // return response.data
}, error => {
  ElMessage({
    message: error || 'Error',
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})

export default service
